import sqlite3 from "sqlite3";
import { getDB } from "./db.js";

export class CodeSnippetsCodebaseIndex {
  relativeExpectedTime = 1;
  artifactId = "codeSnippets";

  static async _createTables(db) {
    await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets (
        id INTEGER PRIMARY KEY,
        path TEXT NOT NULL,
        content TEXT NOT NULL,
        signature TEXT,
        startLine INTEGER NOT NULL,
        endLine INTEGER NOT NULL
    )`);
  }
  
  static async add(datas) {
    const db = await getDB();
    await CodeSnippetsCodebaseIndex._createTables(db);
    for (const data of datas) {
        // 确保所有必要字段都存在并有默认值
        const filePath = data.filePath || '';
        const signature = data.signature || 'anonymous';
        const code = data.code || '';
        const startLine = data.startPosition || 0;
        const endLine = data.endPosition || 0;
        
        db.run(
        `INSERT INTO code_snippets (path, content, signature, startLine, endLine)
        VALUES (?, ?, ?, ?, ?)`,
        [filePath, code, signature, startLine, endLine],
      )}
  }

  static async getAll(signature) {
    const db = await getDB();
    await CodeSnippetsCodebaseIndex._createTables(db);
    try {
      const rows = await db.all(
        `SELECT cs.id, cs.path, cs.signature
        FROM code_snippets cs
        WHERE cs.signature = ?;
        `,
        signature
      );

      // 检查 rows 是否为数组，避免调用 map 方法时出错
      if (Array.isArray(rows)) {
        return rows.map((row) => ({
          title: row.signature || 'Untitled',
          path: row.path,
          id: row.id,
        }));
      }
    } catch (error) {
      console.error("Error fetching code snippets:", error);
    }
    return [];
  }
}